package drds.plus.api;

import drds.plus.sql_process.abstract_syntax_tree.configuration.ColumnMetaData;
import drds.plus.sql_process.type.Type;
import drds.tools.$;

import java.sql.SQLException;
import java.util.List;

public class RowDataMetaData {

    private List<ColumnMetaData> columnMetaDataList;

    public RowDataMetaData(List<ColumnMetaData> columns) {
        this.columnMetaDataList = columns;
    }

    public Type getColumnValueType(String column) {
        for (ColumnMetaData columnMetaData : columnMetaDataList)
            if (column.equalsIgnoreCase(columnMetaData.getColumnName()) || column.equalsIgnoreCase(columnMetaData.getAlias())) {
                return columnMetaData.getType();
            }
        return null;
    }

    public int getColumnCount() throws SQLException {
        return this.columnMetaDataList.size();
    }

    // jdbc规范从1开始，database从0开始，所以减一

    public String getColumnName(int column) throws SQLException {
        column--;
        ColumnMetaData columnObj = this.columnMetaDataList.get(column);
        return columnObj.getColumnName();
    }

    public String getColumnLabel(int column) throws SQLException {
        column--;
        return $.isNotNullAndNotEmpty(this.columnMetaDataList.get(column).getAlias()) ? this.columnMetaDataList.get(column).getColumnName() : this.columnMetaDataList.get(column).getAlias();
    }

    public String getTableName(int column) throws SQLException {
        column--;
        ColumnMetaData c = this.columnMetaDataList.get(column);
        return c.getTableName() == null ? "" : c.getTableName();
    }

    public String getCatalogName(int column) throws SQLException {
        return "drds";
    }

    public int getColumnType(int column) throws SQLException {
        column--;
        ColumnMetaData c = this.columnMetaDataList.get(column);

        Type type = c.getType();
        if (type == null) {
            throw new SQLException("data type is null, column is: " + c);
        }

        return type.getSqlType();
    }

    public String getColumnTypeName(int column) throws SQLException {
        column--;
        ColumnMetaData c = this.columnMetaDataList.get(column);
        return c.getType().toString();
    }

    public List<ColumnMetaData> getColumnMetaDataList() {
        return columnMetaDataList;
    }

    public void setColumnMetaDataList(List<ColumnMetaData> columnMetaDataList) {
        this.columnMetaDataList = columnMetaDataList;
    }

}
